﻿using System;
using System.Collections;
using System.Configuration;
using System.Globalization;
using System.Web.UI;
using System.Web.UI.WebControls;
using mojoPortal.Business;
using mojoPortal.Business.WebHelpers;
using mojoPortal.Web.Framework;
using mojoPortal.Web;
using ud_SwirlingQuestion.Business;
using Resources;
using System.Collections.Generic;

namespace ud_SwirlingQuestion
{
    public partial class AnswerViewControl : UserControl
    {
        #region Properties

        private Hashtable moduleSettings;
        readonly DBSwirlingQuestion repository = new DBSwirlingQuestion();
        protected SwirlingQuestionConfiguration config = new SwirlingQuestionConfiguration();
        private ud_QA item;
        private List<ud_QA> otherArticles;
        private Module module;
        protected string DeleteLinkImage = "~/Data/SiteImages/" + WebConfigSettings.DeleteLinkImage;

        protected int PageId = -1;
        protected int ModuleId = -1;
        protected Guid itemGuid = Guid.Empty;
        protected bool AllowComments;

        protected string CommentDateTimeFormat;
        protected bool parametersAreInvalid;
        protected Double TimeOffset;
        private TimeZoneInfo timeZone;

        protected bool IsEditable;
        protected string EditContentImage = ConfigurationManager.AppSettings["EditContentImage"];
        protected string GmapApiKey = string.Empty;

        protected string blogAuthor = string.Empty;
        protected string SiteRoot = string.Empty;
        protected string ImageSiteRoot = string.Empty;
        private mojoBasePage basePage;

        protected string RegexRelativeImageUrlPatern = @"^/.*[_a-zA-Z0-9]+\.(png|jpg|jpeg|gif|PNG|JPG|JPEG|GIF)$";

        #endregion

        #region OnInit

        override protected void OnInit(EventArgs e)
        {
            Load += Page_Load;
            dpOtherArticles.PreRender += dpOtherArticles_PreRender;
            base.OnInit(e);
            //EnableViewState = UserCanEditPage();
            basePage = Page as mojoBasePage;
            if (basePage == null) return;
            SiteRoot = basePage.SiteRoot;
            ImageSiteRoot = basePage.ImageSiteRoot;
        }

        #endregion

        private void Page_Load(object sender, EventArgs e)
        {
            Page.EnableViewState = true;
            LoadParams();

            if (
                (basePage == null)
                || (!basePage.UserCanViewPage(ModuleId))
            )
            {
                SiteUtils.RedirectToAccessDeniedPage();
                return;
            }

            if (parametersAreInvalid)
            {
                AllowComments = false;
                pnlBlog.Visible = false;
                return;
            }
            LoadSettings();
            //SetupCss();
            //SetupRssLink();
            PopulateLabels();

            if (IsPostBack || ModuleId <= -1 || itemGuid == Guid.Empty) return;
            if (Context.User.Identity.IsAuthenticated)
            {
                if (WebUser.HasEditPermissions(basePage.SiteInfo.SiteId, ModuleId, basePage.CurrentPage.PageId))
                {
                    IsEditable = true;
                }
            }
            PopulateControls();
        }


        void dpOtherArticles_PreRender(object sender, EventArgs e)
        {
            BindOtherArticles();
        }

        protected virtual void PopulateControls()
        {
            if (parametersAreInvalid)
            {
                AllowComments = false;
                pnlBlog.Visible = false;
                return;
            }

            // if not published only the editor can see it
            if (
                ((!item.IsPublished))
                && (!basePage.UserCanEditModule(ModuleId))
                )
            {
                AllowComments = false;
                pnlBlog.Visible = false;
                WebUtils.SetupRedirect(this, SiteUtils.GetCurrentPageUrl());
                return;
            }

            if (IsEditable)
            {
                lnkEdit.Visible = true;
                if (!basePage.UseTextLinksForFeatureSettings)
                {
                    lnkEdit.ImageUrl = basePage.ImageSiteRoot + "/Data/SiteImages/" + EditContentImage;
                    lnkEdit.Text = SwirlingQuestionResource.EditImageAltText;
                }
                else
                {
                    lnkEdit.Text = SwirlingQuestionResource.ButtonEdit;
                }
                lnkEdit.NavigateUrl = basePage.SiteRoot + "/SwirlingQuestion/SwirlingQuestionEdit.aspx?pageid="
                    + PageId.ToInvariantString()
                    + "&item=" + itemGuid
                    + "&mid=" + ModuleId.ToInvariantString();
            }

            basePage.Title = SiteUtils.FormatPageTitle(basePage.SiteInfo, item.Title);
            litTitle.Text = Server.HtmlEncode(item.Title);
            
            //tweetThis1.Visible = config.ShowTweetThisLink;
            //tweetThis1.TitleToTweet = article.Title;


            //fblike.Visible = config.UseFacebookLikeButton && false;
            //fblike.ColorScheme = config.FacebookLikeButtonTheme;
            //fblike.ShowFaces = config.FacebookLikeButtonShowFaces;
            //fblike.HeightInPixels = config.FacebookLikeButtonHeight;
            //fblike.WidthInPixels = config.FacebookLikeButtonWidth;

            //fbshare.Url = Request.Url.ToString();
            //fbshare.Visible = config.UseFacebookLikeButton;

            litStartDate.Text = timeZone != null ? TimeZoneInfo.ConvertTimeFromUtc(item.LastModified, timeZone).ToString(config.DateTimeFormat) : item.LastModified.AddHours(TimeOffset).ToString(config.DateTimeFormat);

            if (blogAuthor.Length == 0) { blogAuthor = item.CreatedByName; }
            litAuthor.Text = string.Format(CultureInfo.InvariantCulture, string.Empty, blogAuthor);
            litDescription.Text = item.Answer;
            litQuestion.Text = item.Question;

            //using (IDataReader dataReader = Article.GetBlogComments(ModuleId, ItemId))
            //{
            //    dlComments.DataSource = dataReader;
            //    dlComments.DataBind();
            //}

            if (Page.Header == null) { return; }

            Literal link = new Literal
                               {
                                   ID = "blogurl",
                                   Text = @"<link rel='canonical' href='"
                                          + SiteRoot
                                          + item.ItemUrl.Replace("~/", "/")
                                          + @"' />"
                               };
            Page.Header.Controls.Add(link);
            BindOtherArticles();
            lblHitCountLabel.Text = item.HitCount.ToString();
        }

        private void BindOtherArticles()
        {
            otherArticles = repository.GetAllOthers(ModuleId, itemGuid);
            lvOtherArticles.DataSource = otherArticles;
            lvOtherArticles.DataBind();
            if (otherArticles.Count.Equals(0))
            { pnlOther.Visible = false; }
            if (otherArticles.Count <= 10)
            { dpOtherArticles.Visible = false; }
        }

        private void PopulateLabels()
        {
            Title1.Header = module.ModuleTitle;
            lnkEdit.ToolTip = SwirlingQuestionResource.ButtonEdit;

            tt1.Visible = config.ShowTweetThisLink;
            tt1.UrlToTweet = Utils.FormatBlogTitleUrl(SiteRoot, item.ItemUrl, item.Guid.ToString(), PageId, ModuleId);
            tt1.TitleToTweet = item.Title;

            fbs1.Visible = config.UseFacebookShareButton;
            fbs1.Url = Utils.FormatBlogTitleUrl(SiteRoot, item.ItemUrl, item.Guid.ToString(), PageId, ModuleId);
            fbs1.Title = item.Title;
            fbs1.ImgUrl = ImageSiteRoot + "/Data/Icon16x16/facebook.png";

            gbb1.Visible = config.UseGoogleBookmarkButton;
            gbb1.Url = Utils.FormatBlogTitleUrl(SiteRoot, item.ItemUrl, item.Guid.ToString(), PageId, ModuleId);
            gbb1.Title = item.Title;
            gbb1.ImgUrl = ImageSiteRoot + "/Data/Icon16x16/google.png";

            //btnPostComment.Text = SwirlingQuestionResource.BlogCommentPostCommentButton;
            //SiteUtils.SetButtonAccessKey(btnPostComment, SwirlingQuestionResource.BlogCommentPostCommentButtonAccessKey);


            //litCommentsClosed.Text = SwirlingQuestionResource.BlogCommentsClosedMessage;
            //litCommentsRequireAuthentication.Text = SwirlingQuestionResource.CommentsRequireAuthenticationMessage;

            lblOtherHeader.Text = config.OtherQA;

            Image imgProgress = upProgress1.FindControl("imgProgress") as Image;
            if (imgProgress == null) return;
            imgProgress.ImageUrl = ImageSiteRoot + "/Data/Icon16x16/updateprogress.gif";
            imgProgress.AlternateText = SwirlingQuestionResource.Loading;
        }

        private void LoadSettings()
        {            
            item = repository.GetOne(itemGuid);
            if (item.AnswerUser != null && item.IsHot != null)
            {
                repository.Update(item.Guid, item.Title, item.Question, item.Answer, item.IsPublished,
                                  item.CreatedByName, item.CreatedByEmail, item.CreatedByPhone,
                                  item.AnswerUser.Value, item.ItemUrl, item.IsHot.Value);
            }
            module = basePage.GetModule(ModuleId);

            if (
                (module.ModuleId == -1)
                || (item.ModuleID == -1)
                || (item.ModuleID != module.ModuleId)
                || (basePage.SiteInfo == null)
                )
            {
                // query string params have been manipulated
                pnlBlog.Visible = false;
                AllowComments = false;
                parametersAreInvalid = true;
                return;
            }

            RegexRelativeImageUrlPatern = SecurityHelper.RegexRelativeImageUrlPatern;

            moduleSettings = ModuleSettings.GetModuleSettings(ModuleId);

            config = new SwirlingQuestionConfiguration(moduleSettings);
            dpOtherArticles.PageSize = config.OthersDetailPageSize;
            if (config.CustomCssClass.Length > 0) { pnlBlog.CssClass += " " + config.CustomCssClass.Replace(" ", string.Empty) + "-detail"; }
        }

        protected string FormatCommentDate(DateTime startDate)
        {
            if (timeZone != null)
            {
                return TimeZoneInfo.ConvertTimeFromUtc(startDate, timeZone).ToString(CommentDateTimeFormat);

            }

            return startDate.AddHours(TimeOffset).ToString(config.DateTimeFormat);

        }

        protected string FormatBlogUrl(string itemUrl, string guid)
        {
            if (itemUrl.Length > 0)
                return SiteRoot + itemUrl.Replace("~", string.Empty);

            return SiteRoot + "/SwirlingQuestion/ViewAnswer.aspx?pageid=" + PageId.ToInvariantString()
                + "&item=" + guid
                + "&mid=" + ModuleId.ToInvariantString();

        }

        protected virtual void SetupRssLink()
        {
            if (WebConfigSettings.DisableBlogRssMetaLink) { return; }
            if (module == null) return;
            if (Page.Master == null) return;
            Control head = Page.Master.FindControl("Head1");
            if (head == null) return;
            Literal rssLink = new Literal
                                  {
                                      Text = @"<link rel=""alternate"" type=""application/rss+xml"" title="""
                                             + module.ModuleTitle + @""" href="""
                                             + GetRssUrl() + @""" />"
                                  };
            head.Controls.Add(rssLink);
        }

        private string GetRssUrl()
        {
            return SiteRoot + "/qa" + ModuleId.ToInvariantString() + "rss.aspx";
        }

        private void LoadParams()
        {
            WebUtils.GetApplicationRoot();
            TimeOffset = SiteUtils.GetUserTimeOffset();
            timeZone = SiteUtils.GetUserTimeZone();
            PageId = WebUtils.ParseInt32FromQueryString("pageid", -1);
            ModuleId = WebUtils.ParseInt32FromQueryString("mid", -1);
            itemGuid = WebUtils.ParseGuidFromQueryString("item", Guid.Empty);

            if (PageId == -1) parametersAreInvalid = true;
            if (ModuleId == -1) parametersAreInvalid = true;
            if (itemGuid == Guid.Empty) parametersAreInvalid = true;
            if (!basePage.UserCanViewPage(ModuleId)) { parametersAreInvalid = true; }
        }

        protected override void Render(HtmlTextWriter writer)
        {
            if (Page.IsPostBack)
            {
                //WebUtils.SetupRedirect(this, Request.RawUrl);
                //return;
            }

            base.Render(writer);
        }

        protected string FormatTooltip(string title, string content)
        {
            //string result = string.Empty;
            //if (config.UseTooltipSettings)
            //{
            //    if (content.Length > config.TooltipMaxCharSettings)
            //    {
            //        content = UIHelper.CreateExcerpt(content, config.TooltipMaxCharSettings, "...");
            //    }
            //    result = "<div class='tooltip'><div class='title-l'></div><div class='title-m'>" + title + "</div><div class='title-r'></div><div class='body'>" + content + "</div></div>";
            //}
            //else
            //{
            //    result = title;
            //}
            return title;
        }

        protected string FormatBlogTitleUrl(string itemUrl, string guid)
        {
            if (itemUrl.Length > 0)
                return SiteRoot + itemUrl.Replace("~", string.Empty);

            return SiteRoot + "/SwirlingQuestion/ViewAnswer.aspx?pageid=" + PageId.ToInvariantString()
                + "&item=" + guid
                + "&mid=" + ModuleId.ToInvariantString();

        }
    }
}